<template>
  <div class="empoyees-container">
    <el-card class="box-card" style="margin:0 0 20px 0">
      <el-button type="primary" @click="addLead">导入</el-button>
      <el-button type="primary" @click="derive">导出</el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="dialogFormVisible = true"
      >新增员工</el-button>
    </el-card>
    <!-- 卡片插件 -->
    <el-card class="box-card ovAt">
      <!-- 员工渲染表格插件 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        style="width: 100%;margin-bottom: 20px;"
        row-key="id"
        border
        :header-cell-style="tableHeaderStyle"
      >
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column prop="username" label="姓名" sortable width="150" />
        <el-table-column prop="mobile" label="手机号" sortable width="150" />
        <el-table-column prop="workNumber" label="工号" sortable width="120" />
        <el-table-column
          prop="formOfEmployment"
          label="聘用形式"
          sortable
          width="150"
          :formatter="formatter"
        />
        <el-table-column
          prop="departmentName"
          label="部门"
          sortable
          width="150"
        />
        <el-table-column
          prop="timeOfEntry"
          label="入职时间"
          sortable
          width="150"
        >
          <template #default="{row}">
            {{ row.timeOfEntry | formatDate }}
          </template>
        </el-table-column>
        <el-table-column prop="whether" label="是否在职" sortable width="150" />
        <el-table-column prop="state" label="状态" sortable width="150" />
        <el-table-column fixed="right" label="操作" width="300" align="center">
          <template slot-scope="scope">
            <el-button
              v-if="checkMenuPermission('detail')"
              type="text"
              size="small"
              @click.native.prevent="checkStaff(scope.$index, tableData)"
            >
              查看
            </el-button>
            <el-button
              type="text"
              size="small"
              @click.native.prevent="turnJust(scope.$index, tableData)"
            >
              转正
            </el-button>
            <el-button type="text" size="small">
              调岗
            </el-button>
            <el-button type="text" size="small">
              离职
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="RoleClick(scope.row.id)"
            >
              角色
            </el-button>
            <el-button
              v-if="checkPointPermission('employees-delete')"
              type="text"
              size="small"
              @click="delRole(scope.$index, tableData)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页插件 -->
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="pagesize"
        layout="total, prev, pager, next"
        :total="total"
        @current-change="handleCurrentChange"
      />
    </el-card>
    <!-- 新增员工对话框弹窗 -->
    <el-dialog title="新增员工" :visible.sync="dialogFormVisible">
      <el-form ref="depForm" :model="form" :rules="rules">
        <el-form-item
          label="姓名:"
          :label-width="formLabelWidth"
          prop="username"
        >
          <el-input
            v-model="form.username"
            autocomplete="off"
            placeholder="2~4个字符"
            class="inpWidth"
          />
        </el-form-item>
        <el-form-item label="手机:" :label-width="formLabelWidth" prop="mobile">
          <el-input
            v-model="form.mobile"
            autocomplete="off"
            placeholder="请输入手机号"
            class="inpWidth"
          />
        </el-form-item>
        <el-form-item
          label="入职时间:"
          :label-width="formLabelWidth"
          prop="timeOfEntry"
        >
          <el-date-picker
            v-model="form.timeOfEntry"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item
          label="聘用形式:"
          :label-width="formLabelWidth"
          form-of-employment
          prop="formOfEmployment"
        >
          <el-select
            v-model="form.formOfEmployment"
            placeholder="请选择聘用形式"
          >
            <el-option
              v-for="(item, index) in hireType"
              :key="index"
              :label="item.id"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="工号:"
          :label-width="formLabelWidth"
          prop="workNumber"
        >
          <el-input
            v-model.number="form.workNumber"
            autocomplete="off"
            placeholder="1~6个字符"
            class="inpWidth"
          />
        </el-form-item>
        <el-form-item
          label="部门:"
          :label-width="formLabelWidth"
          prop="departmentName"
        >
          <el-select
            v-model="form.departmentName"
            placeholder="请选择部门"
            @focus="employeesList"
          >
            <el-option
              v-for="item in departs"
              :key="item.id"
              :label="item.name"
              :value="item.name"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="转正时间:"
          :label-width="formLabelWidth"
          prop="correctionTime"
        >
          <el-date-picker
            v-model="form.correctionTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="addClick">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 员工转正对话框 -->
    <el-dialog title="员工转正" :visible.sync="Visible" class="staffBecome">
      <div class="headData">
        <div class="imgBox">
          <el-avatar :size="100" :src="staffJust.staffPhoto" />
        </div>
        <div class="contentBox">
          <h3>{{ staffJust.username }}</h3>
          <p>
            <span>手机：</span><span>{{ staffJust.mobile }}</span>&nbsp;&nbsp;<span>部门：</span><span>{{ staffJust.departmentName }}</span>
          </p>
          <p>
            <span>入职时间：</span><span>{{ staffJust.correctionTime }}</span>
          </p>
        </div>
      </div>
      <el-divider />
      <el-form ref="depForm" :model="correctionData" :rules="rules">
        <el-form-item label="转正时间:" :label-width="formLabelWidth">
          <el-date-picker
            v-model="correctionData.dateOfCorrection"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="转正评价:" :label-width="formLabelWidth">
          <el-input
            v-model="correctionData.correctionEvaluation"
            type="textarea"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveClick">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 角色分配组件 -->
    <role ref="roleAllot" />
  </div>
</template>

<script>
import {
  // 获取员工列表接口
  getStaffList,
  // 添加员工接口
  addStaff,
  // 删除员工接口板
  delEmployee,
  // 获取员工转正数据接口
  getCorrectionJob,
  // 保存员工转正接口
  saveCorrectionJob
} from '@/api/employees'
import { getDepartmentList } from '@/api/Structure'
import emoHireType from '@/api/constant/employees'
import role from './role/index.vue'
import mixins from '../../mixins'
export default {
  name: 'Empoyees',
  components: { role },
  mixins: [mixins],
  data() {
    // 自定义手机号有没有重复使用的校验
    const mobileVerify = async(rule, value, callback) => {
      const res = await getStaffList(1, 100000000000000)
      res.rows.filter(v => {
        if (v.mobile === value) {
          return true
        } else {
          return false
        }
      }).length === 0
        ? callback()
        : callback(new Error('该手机号已被使用'))
    }
    // 自定义工号有没有重复使用的校验
    const workNumberVerify = async(rule, value, callback) => {
      const res = await getStaffList(1, 10000000000000)
      res.rows.filter(v => {
        if (+v.workNumber === value) {
          return true
        } else {
          return false
        }
      }).length === 0
        ? callback()
        : callback(new Error('该工号已被使用'))
    }
    return {
      // 转正对话框
      Visible: false,
      // loading数据加载动画
      loading: false,
      // 每页显示条数
      pagesize: 5,
      // 总条数
      total: 1,
      // 第几页
      currentPage: 1,
      // 员工表格渲染数据
      tableData: [],
      // 新增员工
      form: {
        username: '', // 姓名
        mobile: '', // 手机号
        workNumber: undefined, // 工号
        formOfEmployment: '', // 聘用形式
        departmentName: '', // 组织名称
        timeOfEntry: '', // 入职时间
        correctionTime: '' // 转正时间
      },
      // 部门数据
      departs: [],
      // 是否显示对话框
      dialogFormVisible: false,
      // 设置对话框左边距
      formLabelWidth: '120px',
      // 表头样式
      tableHeaderStyle: {
        backgroundColor: '#fafafa'
      },
      // 聘用形式渲染
      hireType: emoHireType.hireType,
      // 新增员工表单校验
      rules: {
        username: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { min: 2, max: 4, message: '长度在2~4个字符', trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '不能为空', trigger: 'blur' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式错误',
            trigger: 'blur'
          },
          { validator: mobileVerify, trigger: 'blur' }
        ],
        workNumber: [
          { required: true, message: '不能为空', trigger: 'blur' },
          { validator: workNumberVerify, trigger: 'blur' },
          { type: 'number', message: '只能为纯数字', trigger: 'blur' }
        ],
        formOfEmployment: [
          { required: true, message: '招聘不能为空', trigger: 'blur' }
        ],
        departmentName: [
          { required: true, message: '部门不能为空', trigger: 'blur' }
        ],
        timeOfEntry: [
          { required: true, message: '入职时间不能为空', trigger: 'blur' }
        ],
        correctionTime: [
          { required: true, message: '转正时间不能为空', trigger: 'blur' }
        ]
      },
      // 转正数据
      correctionData: {},
      // 员工数据
      staffJust: {}
    }
  },
  // 页面一加载调用方法获取员工信息
  created() {
    this.getListData(this.currentPage)
  },
  methods: {
    // 获取员工
    async getListData(num) {
      this.loading = true
      const res = await getStaffList(num, this.pagesize)
      const dataRes = res.rows.filter(v => {
        v.whether = '在职'
        v.state = '可用'
        return true
      })
      // 给员工添加状态和在职
      this.tableData = dataRes
      this.total = res.total
      setTimeout(() => {
        this.loading = false
      }, 200)
    },
    // 点击分页切换页码
    async handleCurrentChange(val) {
      this.getListData(val)
    },
    // 新增员工
    addClick() {
      this.$refs.depForm.validate(async v => {
        if (v) {
          const res = await addStaff(this.form)
          this.$message.success('添加成功')
          this.dialogFormVisible = false
          this.getListData(this.currentPage)
          this.form = {
            username: '',
            mobile: '',
            workNumber: undefined,
            formOfEmployment: '',
            departmentName: '',
            timeOfEntry: '',
            correctionTime: ''
          }
        } else {
          return false
        }
      })
    },
    // 点击下拉菜单获取所有部门
    async employeesList() {
      const res = await getDepartmentList()
      const listDataRes = res.depts.filter(v => {
        if (v.code !== '1') {
          return true
        } else {
          return false
        }
      })
      this.departs = listDataRes
      this.getListData()
    },
    // 删除员工
    async delRole(v, tableData) {
      await delEmployee(tableData[v].id)
      if (this.tableData.length === 1) {
        const val = this.currentPage - 1
        this.getListData(val)
      } else {
        this.getListData(this.currentPage)
      }
      this.$message.success('删除角色成功')
    },
    // 查看员工
    checkStaff(index, tableData) {
      // console.log(tableData[index].id)
      this.$router.push({ path: `/details/${tableData[index].id}` })
    },
    // 自定义table渲染
    formatter(row) {
      const res = emoHireType.hireType.find(v => {
        return +row.formOfEmployment === v.id
      })
      return res.value
    },
    // 切换到导入页面
    addLead() {
      this.$router.push('/excel')
    },
    // 导出
    derive() {
      import('@/vendor/Export2Excel').then(excel => {
        const tHeader = Object.keys(this.tableData[0])
        const data = []
        this.tableData.forEach(value => {
          const arr = []
          Object.keys(value).forEach(item => {
            arr.push(value[item])
          })
          data.push(arr)
        })
        excel.export_json_to_excel({
          header: tHeader,
          data,
          filename: 'excel-list',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 获取转正信息
    async turnJust(index, tableData) {
      this.Visible = true
      this.staffJust = tableData[index]
      console.log(this.staffJust)
      const resData = await getCorrectionJob(tableData[index].id)
      this.correctionData = resData
    },
    // 修改转正信息
    saveClick() {
      saveCorrectionJob({ ...this.correctionData })
      this.$message.success('更改成功')
      this.Visible = false
    },
    // 分配角色
    RoleClick(id) {
      this.$refs.roleAllot.getInfoAndShow(id)
    }
  }
}
</script>

<style lang="scss">
.empoyees-container {
  padding: 20px;
  .box-card {
    display: flex;
    justify-content: flex-end;
    .el-button {
      height: 30px;
      padding: 0 15px;
    }
  }
  .ovAt {
    .el-card__body {
      overflow-x: auto;
      .el-button {
        height: 30px;
        padding: 0 5px;
      }
    }
  }
  .el-dialog__header {
    background-color: #66b1ff;
    .el-dialog__title,
    .el-dialog__close {
      color: white;
    }
  }
  .el-dialog__body {
    .el-form-item__label {
      text-align: left;
    }
    padding: 15px 30px;
    .inpWidth {
      width: 50%;
    }
  }
  .el-dialog__footer {
    text-align: center;
    padding: 10px 30px;
  }
  .staffBecome {
    .headData {
      display: flex;
      padding: 30px 0 0px 40px;
      .imgBox {
        margin-right: 20px;
      }
      .contentBox {
        h3 {
          margin: 10px 0;
        }
        p {
          margin: 8px 0;
        }
      }
    }
    .el-form {
      width: 50%;
      .el-form-item__label {
        text-align: right;
      }
    }
  }
}
</style>
